package com.syni.mdd.yhd.common.all.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.syni.mdd.yhd.common.all.dao.jpa.ImgPrefixDao;
import com.syni.mdd.yhd.common.all.entity.ImgPrefix;
import com.syni.mdd.yhd.common.all.service.ImgPrefixService;
import com.syni.mdd.sjb.common.component.utils.common.utils.RequestHeaderData;
import com.syni.mdd.sjb.common.component.utils.common.utils.StringUtils;
import com.syni.mdd.sjb.common.component.utils.common.utils.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.lang.reflect.Field;
import java.net.URL;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @className
 * @description TOO
 * @Author cfx
 * @DATE 2019/4/9 12:04
 * @VERSION 1.0
 **/
@Service
public class ImgPrefixServiceImpl implements ImgPrefixService {
    private final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    ImgPrefixDao imgPrefixDao;

    @Override
    public ImgPrefixDao getBaseDao() {
        return imgPrefixDao;
    }

    //兼容
    private final String tfUrl = "tf.syni.com";

    final int GD_CODE = 1;
    final int QQ_CODE = 2;
    final int GN_CODE = 3;


    private List<ImgPrefix> imgPrefixes = null;
    @PostConstruct
    private void init(){
        log.info("-----------------> imgPrefixes 初始化 <-----------------");
        imgPrefixes = this.getBaseDao().findAll();
    }



    //对对象的图片字段URL做拼接处理
    @Override
    public  void pushSpliceField(Object obj,  String... properies) {

        ImgPrefix imgPrefix = getImgPrefixByCode();

        if(obj == null || imgPrefix == null){
            return;
        }


        if (properies.length > 0) {
            for (String str : properies) {
                try {
                    Field field = obj.getClass().getDeclaredField(str);
                    if (field != null) {
                        if (str.equals(field.getName())) {
                            field.setAccessible(true);

                            if (field.get(obj) != null && StringUtils.isNotBlank(field.get(obj).toString())) {

                                if(WebUtils.isJSONStr(field.get(obj).toString())){
                                    //如果是JSON
                                    List<String> urls = (List<String>) JSON.parse(field.get(obj).toString());
                                    for(int i=0;i<urls.size();i++){
                                        //log.info("------------> url:".concat(urls.get(i)));
                                        if(urls.get(i).contains(tfUrl)){
                                            //log.info("--------> 包含tfUrl 跳过 <---------");
                                            continue;
                                        }
                                        try {
                                            String imgUrl = "";
                                            if (WebUtils.isHttpUrl(urls.get(i))) {
                                                URL url = new URL(urls.get(i));
                                                imgUrl = url.getPath();
                                            } else {
                                                imgUrl = urls.get(i);
                                            }
                                            urls.set(i,imgPrefix.getPrefix().concat(imgUrl));
                                        }catch (Exception e){
                                            log.error(e.getMessage());
                                        }
                                    }


                                    field.set(obj, JSONObject.toJSONString(urls));

                                }else if(!field.get(obj).toString().contains(tfUrl)){
                                    String imgUrl = "";
                                    if(WebUtils.isHttpUrl(field.get(obj).toString())){
                                        URL url = new URL(field.get(obj).toString());
                                        imgUrl = url.getPath();
                                    }else {
                                        imgUrl = field.get(obj).toString();
                                    }
                                    imgUrl = imgPrefix.getPrefix().concat(imgUrl);
                                    field.set(obj,imgUrl);
                                }

                            }
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage());

                }

            }
        }
    }



    //对对象集合的图片字段URL做拼接处理
    @Override
    public void pushSpliceField(List list,  String... properies) {
        ImgPrefix imgPrefix = getImgPrefixByCode();

        if(list == null || imgPrefix == null){
            return;
        }

        if (properies.length > 0) {
            for (String str : properies) {
                for(Object obj : list) {
                    try {
                        if (obj == null) {
                            continue;
                        }
                        Field field = obj.getClass().getDeclaredField(str);
                        if (field != null) {
                            if (str.equals(field.getName())) {
                                field.setAccessible(true);

                                if (field.get(obj) != null && StringUtils.isNotBlank(field.get(obj).toString()) ) {

                                    if(WebUtils.isJSONStr(field.get(obj).toString())){
                                        //如果是JSON
                                        List<String> urls = (List<String>) JSON.parse(field.get(obj).toString());
                                        for(int i=0;i<urls.size();i++){
                                            if(urls.get(i).contains(tfUrl)){
                                                continue;
                                            }
                                            try {
                                                String imgUrl = "";
                                                if (WebUtils.isHttpUrl(urls.get(i))) {
                                                    URL url = new URL(urls.get(i));
                                                    imgUrl = url.getPath();
                                                } else {
                                                    imgUrl = urls.get(i);
                                                }
                                                urls.set(i,imgPrefix.getPrefix().concat(imgUrl));
                                            }catch (Exception e){
                                                log.error(e.getMessage());
                                            }
                                        }


                                        field.set(obj, JSONObject.toJSONString(urls));
                                    }else if(!field.get(obj).toString().contains(tfUrl)){
                                        String imgUrl = "";
                                        if (WebUtils.isHttpUrl(field.get(obj).toString())) {
                                            URL url = new URL(field.get(obj).toString());
                                            imgUrl = url.getPath();
                                        } else {
                                            imgUrl = field.get(obj).toString();
                                        }
                                        imgUrl = imgPrefix.getPrefix().concat(imgUrl);
                                        field.set(obj, imgUrl);
                                    }


                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error(e.getMessage());
                    }
                }
            }
        }
    }

    private ImgPrefix getImgPrefixByCode(){
        RequestHeaderData requestHeaderData = new RequestHeaderData();
        Integer code = requestHeaderData.getInteger("code");
        if(code == null){
            code = 44;
        }
        ImgPrefix imgPrefix = null;
        int codePrefix = Integer.parseInt(code.toString().substring(0,2));

        if(code.toString().startsWith("44")){
            //广东省
            imgPrefix = this.imgPrefixes.stream().filter(v->v.getId() == GD_CODE).collect(Collectors.toList()).get(0);
        }else if(codePrefix >= 11 && codePrefix <= 65){
            //国内
            imgPrefix = this.imgPrefixes.stream().filter(v->v.getId() == GN_CODE).collect(Collectors.toList()).get(0);
        }else{
            //其他地区
            imgPrefix = this.imgPrefixes.stream().filter(v->v.getId() == QQ_CODE).collect(Collectors.toList()).get(0);
        }
        return imgPrefix;
    }
}
